package com.tonghe.filter;

import com.tonghe.pojo.User;
import com.tonghe.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Date:2021/12/3- 12- 03- 20:11
 **/
public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;//通过HttpServletRequest 重定向
        HttpServletResponse response = (HttpServletResponse) resp;//获得Session
//        request.getSession().getAttribute(Constants.USER_SESSION);
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);//过滤器，从session中获取用户

        if(user == null){//已经移除、注销、未登录
            response.sendRedirect(((HttpServletRequest) req).getContextPath()+"/error.jsp");
        }else{
            chain.doFilter(req,resp);
        }
     }

    @Override
    public void destroy() {

    }
}
